Pointers in C by Naveen Toppo & Hrishikesh Dewan

Pointers in C by Naveen Toppo & Hrishikesh Dewan

Author:Naveen Toppo & Hrishikesh Dewan
Language: eng
Format: mobi, epub
ISBN: 9781430259114
Publisher: Apress


Source code. String11.c

#include <stdio.h>

#include <string.h>

#include <malloc.h>

int main(int argc, char* argv[])

{

char* arr[6];

char tempstring[30];

int i;

for(i = 0 ; i< 6;i++)

{

printf("Insert data\n");

scanf("%s",tempstring);

arr[i] = (char*)malloc(sizeof(char)*(strlen(tempstring) + 1));

strcpy(arr[i], tempstring);

}

printf("Data in array");

for(i = 0; i< 6; i++)

{

printf(" %d - %s\n", i, arr[i]);

}

freestring(arr, 5);

return 0;

}

freestring(char arr[], int length)

{

int i;

for( i = 0; i <= length; i++)

{

free(arr[i]);

}

}

Insert data

EGRET

Insert data

IBIS

Insert data

MYNA

Insert data

IORA

Insert data

MUNIA

Insert data

BULBUL

Data in array

0 – EGRET

1 – IBIS

2 – MYNA

3 – IORA

4 – MUNIA

5 – BULBUL

The freestring(char arr[], int length) method takes the address of a character array and its length. The code shown above has only assigned (dynamic allocation) space for the character strings during each iteration and it is pointed to by character pointers that are stored at each index of the array. So, in the freestring() method, every dynamically assigned memory is freed/deallocated during each iteration.

Now let’s see the third way of declaring arrays of strings when size of array and capacity of each array index to hold the data is not known at compile time. This method of declaration is also known as a pointer-to-pointer declaration. Let’s assume that we have the following declaration in the program:

char** dynamic_str;

Figure 4-4 illustrates the memory layout of the array of strings when pointer-to-pointer declaration is used. The reader can see that the data stored in the memory with respect to each index is of variable length.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.